<script setup>
    import reserveApi from "@/api/reserve.js";
    import {ref} from "vue";
    import {ElMessage, ElMessageBox} from "element-plus";
    import {Plus} from '@element-plus/icons-vue'
    import courseApi from "@/api/course.js";
    import userApi from "@/api/user.js";

    import {useUserInfoStore} from '@/store/userInfo.js'
    const userInfoStore = useUserInfoStore()
    const userId = userInfoStore.user.id //从userInfoStore（pinia取出用户id）

    //数据表格
    const list = ref([])//当前页数据
    const total = ref(0)//总条目数

    //分页信息和搜索条件
    const reserveQuery = ref({
        name: '',
        userId: '',
        reserveId: '',
        courseId: '',
        page: 1,
        limit: 10
    })

    //调用reserveApi.listByUserId查找信息
    const loadData = () => {//加载数据，分页查找
        reserveQuery.value.userId = userId
        reserveApi.listByUserId(reserveQuery.value).then(result => {
            if(result.code == 0) {
                list.value = result.data.records//当前页数据
                total.value = result.data.total//总条目数
            }
        })
    }

    loadData()//调用

    //条件查找，拼接条件在后端mapper已经实现
    const onSearch = () => {
        reserveQuery.value.page = 1
        loadData()
    }

    //重置搜索框为空
    const reset = () => {
        reserveQuery.value.name = ''
        reserveQuery.value.reserveId = ''
        reserveQuery.value.beginUpdateTime = ''
        reserveQuery.value.endUpdateTime = ''
    }

    //按id删除
    const deleteById = (id) => {
        ElMessageBox.confirm(
            '您确认要删除吗?',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        ).then(() => {
            reserveApi.deleteById(id).then(result => {
                if (result.code == 0) {
                    ElMessage.success(result.msg)
                    loadData()
                } else {
                    ElMessage.error(result.msg)
                }
            })
        })
    }

    //批量删除
    //1.双向绑定将前台勾选的id存进数组
    const ids = ref([])
    const handleSelectionChange = (rows) => {
        console.log('多选',rows)
        ids.value = rows.map(row => row.id)
        console.log(ids.value)
    }
    //执行批量删除
    const deleteAll = () => {
        ElMessageBox.confirm(
            '您确认要删除吗?',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        ).then(() => {
            reserveApi.deleteAll(ids.value).then(result => {
                if (result.code == 0) {
                    ElMessage.success(result.msg)
                    loadData()//成功后重新加载数据，分页查找
                } else {
                    ElMessage.error(result.msg)
                }
            })
        })
    }

    //添加、编辑
    const dialogAddVisible = ref(false)//点击前默认不显示
    const dialogFormVisible = ref(false)//点击前默认不显示
    const reserve = ref({})//ref:双向绑定，reserve为前台输入要添加编辑的对象，ref里的参数vue动态地帮我加上去了



    //更新update
    //编辑（更新）弹出框逻辑
    const showUpdateDialog = (id) => {
        dialogFormVisible.value = true//弹出对话框
        reserveApi.selectById(id).then(result => {
            if (result.code == 0) {//result.code==0 证明查找成功
                reserve.value = result.data //result.data查找结果的值（旧值）赋值给双向绑定的reserve.value（新值）
            }
        })
    }
    //调用reserveApi.update执行更新
    const updateReserve = () => {
        if (reserve.value.id) {
            reserveApi.update(reserve.value).then(result => {
                if (result.code == 0) { //js里有非空值就代表true
                    ElMessage.success(result.msg)
                    dialogFormVisible.value = false//更新完自动关闭对话框
                    loadData()//成功后重新加载数据，分页查找
                } else {
                    ElMessage.error(result.msg)
                }
            })
        }
    }

    //添加add
    //添加弹出框逻辑（准备好信息发送添加ajax请求）
    const showAddDialog = () => {
        reserve.value = {
            userId: userId,
        }  //本来是reserve.value = {} 清空对话框上一次留下的数据，否则会由于双向绑定把上一次添加的数据回显，但这里的用户id需要，所有赋了值
        dialogAddVisible.value = true//触发点击事件showAddDialog后显示
    }
    //调用reserveApi.add执行添加（提交表单发送添加ajax请求）
    const addReserve = () => {
        {
            reserveApi.add(reserve.value).then(result => {
                if (result.code == 0) {
                    ElMessage.success(result.msg)
                    dialogAddVisible.value = false//添加完自动关闭对话框
                    loadData()//成功后重新加载数据，分页查找
                } else {
                    ElMessage.error(result.msg)
                }
            })
        }
    }


    //查找所有的用户
    const userList = ref([])
    userApi.selectAll().then(result => {
        if (result.code == 0) {
            userList.value = result.data
        }
    })

    //查找所有的课程
    const courseList = ref([])
    courseApi.selectAll().then(result => {
        if (result.code == 0) {
            courseList.value = result.data
        }
    })

    //下拉事件
    const selectChange = (value) => {
        console.log(value)
    }
</script>

<template>
    <el-card class="">
        <!-- header表头 -->
        <template #header>
            <div class="header">
                <el-button type="primary" @click="showAddDialog">添加</el-button>
                <el-button type="primary" @click="deleteAll">批量删除</el-button>
            </div>
        </template>
        <el-form :inline="true">
            <el-form-item label="课程">
                <el-select @change="selectChange" v-model="reserveQuery.courseId" placeholder="请选择课程" clearable
                           style="width: 240px">
                    <el-option
                        v-for="course in courseList"
                        :key="course.id"
                        :label="course.name"
                        :value="course.id"
                    />
                </el-select>
            </el-form-item>
            <!--reserveQuery里没有beginUpdateTime这两个属性，后端java代码CourseQuery对象里一定要加上，但是vue很智能会自动加上，所以前端代码ref里不用写也可以-->
            <el-form-item label="更新时间" :label-width="100">
                <el-date-picker
                    v-model="reserveQuery.beginUpdateTime"
                    type="datetime"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="开始时间"
                />
                <el-date-picker
                    v-model="reserveQuery.endUpdateTime"
                    type="datetime"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="结束时间"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSearch">搜索</el-button>
                <el-button type="warning" @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
        <!-- 表中间遍历输出表格内容 -->
        <el-table :data="list" style="width: 100%" ref="multipleTableRef" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"/>
            <el-table-column fixed prop="id" label="ID"/>
            <el-table-column prop="userId" label="用户id"/>
            <el-table-column prop="userName" label="用户"/>
            <el-table-column prop="courseId" label="课程id"/>
            <el-table-column prop="courseName" label="课程"/>
            <el-table-column prop="score" label="评分" width="180px"/>
            <el-table-column prop="comment" label="评论"/>
            <el-table-column prop="updateTime" label="更新时间" width="180px"/>
            <el-table-column align="center" width="200px" fixed="right" label="操作">
                <template #default="{ row }"><!--解构赋值-->
                    <el-button size="small" type="primary" @click="showUpdateDialog(row.id)">评价</el-button>
                    <el-button size="small" type="danger" @click="deleteById(row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!--底部分页-->
        <el-pagination
            v-model:current-page="reserveQuery.page"
            v-model:page-size="reserveQuery.limit"
            :page-sizes="[10, 20, 30, 40]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @change="loadData"
            style="margin-top: 20px; justify-content: flex-end"
        />
    </el-card>
    <!--添加、编辑弹出框-->
    <!--添加弹出框-->
    <el-dialog v-model="dialogAddVisible" :title="title" width="60%" :lock-scroll="false">
        <el-form :model="reserve">
            <el-form-item label="课程" :label-width="80">
                <el-select v-model="reserve.courseId" placeholder="请选择课程" style="width: 240px">
                    <el-option
                        v-for="course in courseList"
                        :key="course.id"
                        :label="course.name"
                        :value="course.id"
                    />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogAddVisible = false">取消</el-button>
                <el-button type="primary" @click="addReserve">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>

    <!--评价弹出框-->
    <el-dialog v-model="dialogFormVisible" :title="title" width="60%" :lock-scroll="false">
        <el-form :model="reserve">
            <el-form-item label="评分" :label-width="80">
                <el-input-number :min="1" :max="5" step="1" v-model="reserve.score" autocomplete="off" />
            </el-form-item>
            <el-form-item label="评价" :label-width="80">
                <el-input v-model="reserve.comment" autocomplete="off" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="updateReserve">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style scoped>
    .avatar-uploader .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>

<style>
    .avatar-uploader .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader .el-upload:hover {
        border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
    }
</style>